package com.dimples.controller.system;

import com.dimples.common.annotation.OpsLog;
import com.dimples.common.enums.FileServerType;
import com.dimples.common.enums.OpsLogTypeEnum;
import com.dimples.common.properties.DimplesProperties;
import com.dimples.common.transport.Result;
import com.dimples.controller.view.BaseWebController;
import com.dimples.system.factory.FileServiceFactory;
import com.dimples.system.service.SysFileService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/26
 */
@Slf4j
@Api(tags = "消息管理")
@RestController
@RequestMapping(value = BaseWebController.API_SYSTEM_PREFIX + "file")
@RequiredArgsConstructor
public class SysFileController {

    private final DimplesProperties properties;

    SysFileService getFileService() {
        return FileServiceFactory.fileService(properties.getFile().getFtpUse() ? FileServerType.FTP : FileServerType.HTTP);
    }

    @ApiOperation(value = "文件下载")
    @ApiOperationSupport(order = 1)
    @OpsLog(value = "文件下载", type = OpsLogTypeEnum.DOWNLOAD)
    @GetMapping("download/{id}")
    public void download(@PathVariable("id") String id) {
        getFileService().download(id);
    }

    @ApiOperation(value = "文件上传")
    @ApiOperationSupport(order = 3)
    @OpsLog(value = "文件上传", type = OpsLogTypeEnum.UPLOAD)
    @PostMapping("upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        String result = getFileService().upload(file);
        if (StrUtil.isNotBlank(result)) {
            return Result.success(result);
        } else {
            return Result.failed("上传失败");
        }
    }
}
